<template>
    <div class="login-container">
        <el-card class="login-card">
            <h3 class="login-title">管理员登录</h3>
            <el-form ref="ruleFormRef" :model="loginForm" :rules="rules" label-width="75px" class="demo-ruleForm"
                :size="formSize" status-icon>
                <el-form-item label="用户名" prop="userName">
                    <el-input v-model="loginForm.adminName" />
                </el-form-item>
                <el-form-item label="密码" prop="userPwd">
                    <el-input type="password" v-model="loginForm.adminPwd" show-password />
                </el-form-item>
                <el-form-item label="验证码" prop="verifyCode">
                    <div style="flex: 1; display: flex; align-items: center;">
                        <el-input v-model="loginForm.verifyCode" style="flex: 1;" />
                        <img :src="verifyCodeUrl" style="width: 100px;" @click="refreshVerifyCode" />
                    </div>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="submitForm(ruleFormRef)">
                        登录
                    </el-button>
                    <el-button @click="toRegister()">注册</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>
    
<script lang="ts" setup>
import { reactive, ref, computed } from 'vue'
import { ElNotification, type FormInstance, type FormRules } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import api from '@/api'

const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const loginForm = ref({
    adminName: '',
    adminPwd: '',
    verifyCode: ''
})

const rules = reactive<FormRules>({
    adminName: [
        {
            required: true,
            message: '用户名不能为空',
            trigger: 'change',
        },
    ],
    adminPwd: [
        {
            required: true,
            message: '密码不能为空',
            trigger: 'change',
        },
    ],
    verifyCode: [
        {
            required: true,
            message: "请输入验证码",
            trigger: "change"
        },
    ],
})

const store = useStore();
const router = useRouter();

const submitForm = async (formEl: FormInstance | undefined) => {
    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            api.admin.adminlogin(loginForm.value)
                .then(response => {
                    // 在这里可以处理提交成功后的逻辑
                    // 存储 token
                    store.commit('setToken', response.data.token)
                    store.commit('setRoleId', "1")
                    store.commit('admin/updateAdminInfo', response.data.data);
                    ElNotification({
                        title: 'Success',
                        message: response.data.msg,
                        type: 'success',
                        duration: 1500
                    })
                    router.push('/adminhome')
                })
                .catch(error => {
                    ElNotification({
                        title: 'Error',
                        message: error.data.msg,
                        type: 'error',
                        duration: 1500
                    })
                    // 在这里可以处理提交失败后的逻辑
                });
        } else {
            console.log('error submit!', fields)
        }
    })
}

const resetForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.resetFields()
}

const toRegister = () => {
    router.push('/register')
}

const timestamp = ref(Date.now()); // 使用 ref() 函数来声明响应式变量

// 使用 computed() 函数来生成验证码图片 URL
const verifyCodeUrl = computed(() => {
    return `http://localhost:8888/verifyCode/getVerifyCode?timestamp=${timestamp.value}`;
})

// 定义刷新验证码图片的函数
const refreshVerifyCode = () => {
    timestamp.value = Date.now();
}

</script>

<style scoped>
.login-container {
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.login-card {
    width: 400px;
    padding: 20px;
}

.login-title {
    text-align: center;
    margin-bottom: 20px;
}
</style>